package com.army.study.comicqixi.slice;

import com.army.study.comicqixi.ResourceTable;
import com.army.study.comicqixi.SendServiceAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.ElementName;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.event.commonevent.*;
import ohos.global.configuration.Configuration;
import ohos.rpc.IRemoteObject;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.List;

/**
 * Full screen ability slice
 */
public class MainAbilitySlice extends AbilitySlice {
    private TextField fourText;
    private TextField eightText;

    private IRemoteObject remoteObject;
//    private CommonEventSubscriber subscriber;

    private IAbilityConnection connection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            remoteObject = iRemoteObject;
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {

        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        // hide status bar
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);

        // adapt orientation
        int orientation = getResourceManager().getConfiguration().direction;
        if (orientation == Configuration.DIRECTION_HORIZONTAL) {
            super.setUIContent(ResourceTable.Layout_land_main);
        } else {
            super.setUIContent(ResourceTable.Layout_port_main);
        }

        // 初始化组件
        initComponent();
        // 连接发送信息Service
        connectionSendService();
//        // 订阅公共事件
//        subscriberEvent();
    }

//    private void subscriberEvent() {
//        MatchingSkills matchingSkills = new MatchingSkills();
//        matchingSkills.addEvent("sendEvent");  // 此sendEvent由SendServiceAbility::onRemoteRequest定义
//        CommonEventSubscribeInfo info = new CommonEventSubscribeInfo(matchingSkills);
//
//        subscriber = new CommonEventSubscriber(info) {
//            @Override
//            public void onReceiveEvent(CommonEventData commonEventData) {
//                String fourText = commonEventData.getIntent().getStringParam("fourText");
//                String eightText = commonEventData.getIntent().getStringParam("eightText");
//
//                System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
//                System.out.print("FourText: " + fourText);
//                System.out.println("EightText: " + eightText);
//                System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
//
//            }
//        };
//
//
//        try {
//            CommonEventManager.subscribeCommonEvent(subscriber);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
//    }

    private void initComponent() {
        fourText = (TextField)findComponentById(ResourceTable.Id_four);
        eightText = (TextField)findComponentById(ResourceTable.Id_eight);

        Button btnSend = (Button)findComponentById(ResourceTable.Id_btnSend);
        btnSend.setClickedListener(this::btnSendClick);
    }

    private void btnSendClick(Component component) {
//        // 连接发送信息Service
//        connectionSendService();

        MessageParcel data = MessageParcel.obtain();
        data.writeString(fourText.getText());
        data.writeString(eightText.getText());
        MessageParcel reply = MessageParcel.obtain();
        MessageOption option = new MessageOption(MessageOption.TF_SYNC);

        try {
            remoteObject.sendRequest(0, data, reply, option);

            // 提示信息
            new ToastDialog(getContext())
                    .setText("信息已发出，请查看服务卡片")
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void connectionSendService() {
        // 获取所有在线设备ID
        List<DeviceInfo> deviceInfoList = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
        if (deviceInfoList == null || deviceInfoList.isEmpty()) { return; }
        List<String> deviceIdList = new ArrayList<>();
        for (DeviceInfo deviceInfo : deviceInfoList) {
            deviceIdList.add(deviceInfo.getDeviceId());
        }
//        // 本地设备ID
//        String localDeviceId = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(MainAbilitySlice.this)).getLocalDeviceInfo().getId();
//        deviceIdList.add(localDeviceId);

        for (String deviceId : deviceIdList) {
            System.out.println("*********************");
            System.out.println("DeviceId: " + deviceId);
            System.out.println("*********************");
            Intent intentService = new Intent();
            Operation operation =
                    new Intent.OperationBuilder()
                            .withDeviceId(deviceId)
                            .withBundleName(getBundleName())
                            .withAbilityName(SendServiceAbility.class.getName())
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
            intentService.setOperation(operation);
            connectAbility(intentService, connection);
        }

//        // 启动SendServiceAbility
//        Intent intentService = new Intent();
////        intentService.setParam("fourText", fourText.getText());
////        intentService.setParam("eightText", eightText.getText());
//        Operation operation =
//                new Intent.OperationBuilder()
//                        .withDeviceId("")
//                        .withBundleName(getBundleName())
//                        .withAbilityName(SendServiceAbility.class.getName())
//                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
//                        .build();
//        intentService.setOperation(operation);
//        connectAbility(intentService, connection);
////        startAbility(intentService);
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);

        if (displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE) {
            setUIContent(ResourceTable.Layout_land_main);
        } else {
            setUIContent(ResourceTable.Layout_port_main);
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        System.out.println("[onStop] start to destroy slice");
        // 断开发送信息Service
        disconnectAbility(connection);
//        // 取消公共事件
//        try {
//            CommonEventManager.unsubscribeCommonEvent(subscriber);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
    }
}
